package org.hank.demoproject.room

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import org.hank.demoproject.R
import org.hank.demoproject.databinding.ActivityRoomBinding
import org.hank.roomdemo.UserInfo

class RoomActivity : AppCompatActivity() {
    lateinit var binding: ActivityRoomBinding
    lateinit var viewModel: RoomViewModel
    lateinit var roomAdapter: RoomAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_room)
        viewModel = ViewModelProvider(this).get(RoomViewModel::class.java)
        initClick()
        roomAdapter = RoomAdapter(ArrayList<UserInfo>())
        binding.recycler.apply {
            adapter = roomAdapter
            layoutManager = LinearLayoutManager(this@RoomActivity)
        }
        viewModel.userList.observe(this) {
            roomAdapter.submitList(it)
            roomAdapter.notifyDataSetChanged()
        }
        supportActionBar!!.title = "Room"
    }

    override fun onResume() {
        super.onResume()
        viewModel.query()
    }

    fun initClick() {
        binding.apply {
            btnInsert.setOnClickListener {
                var userInfo = UserInfo()
                userInfo.userName = "hank${(Math.random() * 100).toInt()}"
                userInfo.userPassword = "123456"
                userInfo.hobby = "乒乓球"
                userInfo.age = ((Math.random() * 10 * 10) + (Math.random() * 10)).toInt()
                viewModel.insert(userInfo)
            }
            btnDel.setOnClickListener {
                var list = viewModel.userList.value
                if (list!!.size != 0)
                    viewModel.del(list.get(list.lastIndex))
            }
            btnUpdate.setOnClickListener {
                var list = viewModel.userList.value
                if (list!!.size != 0) {
                    var userinfo = list.get(list.lastIndex)
                    userinfo.hobby = "updated"
                    viewModel.update(userinfo)
                }
            }
            btnQuery.setOnClickListener {
                viewModel.query()
            }
        }
    }
}